require 'rake/clean'
require 'albacore'

COMPILE_TARGET = 'release'
CLR_VERSION = 'v3.5'

PROJECT_PATH = Dir.pwd
SRC_PATH = PROJECT_PATH + '/src'
BUILD_ASSEMBLY_OUTPUT_PATH = PROJECT_PATH + '/build/assemblies'
BUILD_WEB_OUTPUT_PATH = PROJECT_PATH + '/build/web'
BUILD_REPORTS_OUTPUT_PATH = PROJECT_PATH + '/build/reports'
BUILD_ARCHIVE_OUTPUT_PATH = PROJECT_PATH + '/build-archive'
MSPEC_CONSOLE_RUNNER_FILE_PATH = PROJECT_PATH + '/tools/MSpec/Machine.Specifications.ConsoleRunner.exe'
SCHEMA_GENERATOR_FILE_PATH = BUILD_ASSEMBLY_OUTPUT_PATH + '/ECommerce.SchemaGenerator.exe'

BUILD_ASSEMBLY_OUTPUT_ENVIRONMENT_CONFIGS_PATH = BUILD_ASSEMBLY_OUTPUT_PATH + '/EnvironmentConfigs'

ENVIRONMENT = ENV['environment'] ? ENV['environment'] : ENV['computername']

task :default => ['clean', 'build:all']

CLEAN.include('build')

namespace :build do
  
	task :all => [:build, :migrate_environment_configs, :create_build_archive, :generate_database_schema, :run_specs]

	desc 'Build web application'
	task :build do				
		frameworkDir = File.join(ENV['windir'].dup, 'Microsoft.NET', 'Framework', CLR_VERSION)
		msbuildFile = File.join(frameworkDir, 'msbuild.exe')		

		get_solution_files.each do |solutionFile|		
			sh "#{msbuildFile} #{solutionFile} /p:Configuration=#{COMPILE_TARGET} /p:OutDir=#{BUILD_ASSEMBLY_OUTPUT_PATH}/ /p:WebProjectOutputDir=#{BUILD_WEB_OUTPUT_PATH} /t:Rebuild /v:m"	
		end
	end
	
	def get_solution_files()
		FileList["#{SRC_PATH}/*.sln"]
	end
	
	desc 'Migrate environment configs'
	task :migrate_environment_configs do		
		FileUtils.cp_r("#{BUILD_ASSEMBLY_OUTPUT_ENVIRONMENT_CONFIGS_PATH}/#{ENVIRONMENT}/.", BUILD_ASSEMBLY_OUTPUT_PATH)
	end
	
	desc 'Create build archive'
	zip :create_build_archive do |zip|				
		FileUtils.mkdir(BUILD_ARCHIVE_OUTPUT_PATH) unless File.directory? BUILD_ARCHIVE_OUTPUT_PATH
		
		time = Time.new
		
		archive_file_name = time.getutc.strftime('%Y%m%d-%H%M%S.zip')
		
		zip.directories_to_zip BUILD_WEB_OUTPUT_PATH
		zip.output_file = archive_file_name
		zip.output_path = BUILD_ARCHIVE_OUTPUT_PATH
	end
	
	desc 'Generate database schema'
	task :generate_database_schema do
		sh SCHEMA_GENERATOR_FILE_PATH
	end
  
	desc 'Run specifications'
	task :run_specs do
		FileUtils.mkdir(BUILD_REPORTS_OUTPUT_PATH)
		
		get_spec_files.each do |specFile|			
			sh "#{MSPEC_CONSOLE_RUNNER_FILE_PATH} #{specFile} --html #{BUILD_REPORTS_OUTPUT_PATH}"
		end
	end
	
	def get_spec_files()
		FileList["#{BUILD_ASSEMBLY_OUTPUT_PATH}/*Specs.dll"]
	end
  
end
